<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SLOCCount - Count Lines of Code</title>
    <style>
        * {
            box-sizing: border-box;
        }
        body {
            font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        h1 {
            margin-bottom: 10px;
            font-size: 28px;
        }
        p {
            margin-top: 0;
            color: #666;
        }
        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            border-bottom: 2px solid #ddd;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background: none;
            border: none;
            border-bottom: 3px solid transparent;
            font-size: 16px;
            color: #666;
            transition: all 0.3s;
        }
        .tab.active {
            color: #ffffff;
            background-color: #007bff;
            border-bottom-color: #007bff;
            font-weight: 600;
        }
        .tab:hover:not(.active) {
            color: #0056b3;
        }
        .tab.active:hover {
            color: #ffffff;
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #333;
        }
        input[type="text"], textarea {
            width: 100%;
            padding: 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            font-size: 16px;
            font-family: inherit;
        }
        textarea {
            font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
            min-height: 200px;
            resize: vertical;
        }
        .input-group {
            margin-bottom: 20px;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }
        button {
            padding: 12px 24px;
            cursor: pointer;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 500;
            transition: background-color 0.3s;
        }
        button:hover:not(:disabled) {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: wait;
            opacity: 0.7;
        }
        button.secondary {
            background-color: #6c757d;
        }
        button.secondary:hover:not(:disabled) {
            background-color: #545b62;
        }
        #status {
            padding: 12px;
            margin-bottom: 20px;
            border-radius: 4px;
            display: none;
        }
        #status.visible {
            display: block;
        }
        #status.info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        #status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        #status.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        #results {
            display: none;
        }
        #results.visible {
            display: block;
        }
        .results-header {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 4px;
            margin-bottom: 20px;
        }
        .results-header h2 {
            margin: 0 0 10px 0;
            font-size: 20px;
        }
        .summary {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        .summary-item {
            background: white;
            padding: 15px;
            border-radius: 4px;
            border: 1px solid #dee2e6;
            text-align: center;
        }
        .summary-item .label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
        }
        .summary-item .value {
            font-size: 28px;
            font-weight: bold;
            color: #007bff;
        }
        .language-breakdown {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            overflow: hidden;
        }
        .language-breakdown h3 {
            margin: 0;
            padding: 15px;
            background-color: #f8f9fa;
            font-size: 18px;
            border-bottom: 1px solid #dee2e6;
        }
        .language-table {
            width: 100%;
            border-collapse: collapse;
        }
        .language-table th {
            background-color: #f8f9fa;
            padding: 12px;
            text-align: left;
            font-weight: 600;
            border-bottom: 2px solid #dee2e6;
        }
        .language-table td {
            padding: 12px;
            border-bottom: 1px solid #dee2e6;
        }
        .language-table tr:last-child td {
            border-bottom: none;
        }
        .language-table tr:hover {
            background-color: #f8f9fa;
        }
        .language-name {
            font-weight: 500;
        }
        .percentage {
            color: #666;
            font-size: 14px;
        }
        @media (max-width: 600px) {
            body {
                padding: 10px;
            }
            h1 {
                font-size: 24px;
            }
            .tabs {
                overflow-x: auto;
            }
            .tab {
                padding: 8px 16px;
                font-size: 14px;
            }
            .button-group {
                flex-direction: column;
            }
            button {
                width: 100%;
            }
            .summary {
                grid-template-columns: 1fr 1fr;
            }
            .summary-item .value {
                font-size: 24px;
            }
            .language-table {
                font-size: 14px;
            }
            .language-table th,
            .language-table td {
                padding: 8px;
            }
        }
    </style>
</head>
<body>
    <h1>SLOCCount - Count Lines of Code</h1>
    <p>Analyze source code to count physical Source Lines of Code (SLOC) using Perl and C programs running via WebAssembly</p>
    <p style="font-size: 14px; margin-top: -10px;">Based on <a href="https://dwheeler.com/sloccount/">SLOCCount</a> by David A. Wheeler</p>

    <div class="tabs">
        <button class="tab active" data-tab="paste">Paste Code</button>
        <button class="tab" data-tab="github">GitHub Repository</button>
        <button class="tab" data-tab="zip">Upload ZIP</button>
    </div>

    <div id="paste-tab" class="tab-content active">
        <div class="input-group">
            <label for="code-input">Paste your code here:</label>
            <textarea id="code-input" placeholder="Paste source code files here (supports multiple files)..."></textarea>
        </div>
        <div class="input-group">
            <label for="filename-input">Filename (to detect language):</label>
            <input type="text" id="filename-input" placeholder="e.g., main.py, app.js, index.html">
        </div>
        <div class="button-group">
            <button id="analyze-paste-btn" disabled>Initializing...</button>
            <button id="clear-paste-btn" class="secondary">Clear</button>
        </div>
    </div>

    <div id="github-tab" class="tab-content">
        <div class="input-group">
            <label for="repo-input">GitHub Repository URL:</label>
            <input type="text" id="repo-input" placeholder="https://github.com/owner/repo">
        </div>
        <div class="button-group">
            <button id="analyze-repo-btn" disabled>Initializing...</button>
        </div>
    </div>

    <div id="zip-tab" class="tab-content">
        <div class="input-group">
            <label for="zip-input">Upload ZIP file containing source code:</label>
            <input type="file" id="zip-input" accept=".zip" style="padding: 10px; border: 2px dashed #ccc; border-radius: 4px; cursor: pointer;">
            <p style="margin-top: 10px; font-size: 14px; color: #666;">
                Useful for large repositories. Upload a ZIP file containing your source code.
            </p>
        </div>
        <div class="button-group">
            <button id="analyze-zip-btn" disabled>Initializing...</button>
        </div>
    </div>

    <div id="status"></div>

    <div id="results">
        <div class="results-header">
            <h2>Analysis Results</h2>
        </div>
        <div class="summary">
            <div class="summary-item">
                <div class="label">Total Lines</div>
                <div class="value" id="total-lines">0</div>
            </div>
            <div class="summary-item">
                <div class="label">Languages</div>
                <div class="value" id="total-languages">0</div>
            </div>
            <div class="summary-item">
                <div class="label">Files</div>
                <div class="value" id="total-files">0</div>
            </div>
            <div class="summary-item">
                <div class="label">Est. Cost (USD)<a href="#cost-estimates-info" style="text-decoration: none; color: #007bff; margin-left: 2px;"><sup>*</sup></a></div>
                <div class="value" id="total-cost">$0</div>
            </div>
            <div class="summary-item">
                <div class="label">Est. Person-Years<a href="#cost-estimates-info" style="text-decoration: none; color: #007bff; margin-left: 2px;"><sup>*</sup></a></div>
                <div class="value" id="total-effort">0</div>
            </div>
        </div>
        <div class="language-breakdown">
            <h3>Language Breakdown</h3>
            <table class="language-table" id="language-table">
                <thead>
                    <tr>
                        <th>Language</th>
                        <th>Lines</th>
                        <th>Percentage</th>
                        <th>Files</th>
                    </tr>
                </thead>
                <tbody id="language-tbody">
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/jszip@3.10.1/dist/jszip.min.js"></script>
    <script src="./lib/webperl/webperl.js"></script>
    <script>
        console.log('Script starting...');
        const tabs = document.querySelectorAll('.tab');
        const pasteTab = document.getElementById('paste-tab');
        const githubTab = document.getElementById('github-tab');
        const zipTab = document.getElementById('zip-tab');
        const codeInput = document.getElementById('code-input');
        const filenameInput = document.getElementById('filename-input');
        const repoInput = document.getElementById('repo-input');
        const zipInput = document.getElementById('zip-input');
        const analyzePasteBtn = document.getElementById('analyze-paste-btn');
        const analyzeRepoBtn = document.getElementById('analyze-repo-btn');
        const analyzeZipBtn = document.getElementById('analyze-zip-btn');
        const clearPasteBtn = document.getElementById('clear-paste-btn');
        const statusEl = document.getElementById('status');
        const resultsEl = document.getElementById('results');

        // Salary input is defined later in HTML, get it lazily
        let salaryInputEl = null;
        function getSalaryInput() {
            if (!salaryInputEl) {
                salaryInputEl = document.getElementById('salary-input');
            }
            return salaryInputEl;
        }

        // Store current analysis files for recalculation
        let currentFiles = null;

        let perlReady = false;
        let slocScripts = {};

        // Recalculate estimates with new salary
        async function recalculateWithSalary() {
            if (!currentFiles || currentFiles.length === 0) {
                return; // No analysis to recalculate
            }

            const salary = parseInt(getSalaryInput().value) || 56286;

            try {
                showStatus('Recalculating with new salary...', 'info');
                const results = await runSloccount(currentFiles, salary);
                displayResults(results);
                hideStatus();
            } catch (error) {
                showStatus('Recalculation failed: ' + error.message, 'error');
                console.error('Recalculation error:', error);
            }
        }

        // Tab switching
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                const tabName = tab.dataset.tab;
                pasteTab.classList.toggle('active', tabName === 'paste');
                githubTab.classList.toggle('active', tabName === 'github');
                zipTab.classList.toggle('active', tabName === 'zip');
            });
        });

        // Clear button
        clearPasteBtn.addEventListener('click', () => {
            codeInput.value = '';
            filenameInput.value = '';
            hideResults();
        });

        // Status helpers
        function showStatus(message, type = 'info', isHtml = false) {
            if (isHtml) {
                statusEl.innerHTML = message;
            } else {
                statusEl.textContent = message;
            }
            statusEl.className = `visible ${type}`;
        }

        function hideStatus() {
            statusEl.className = '';
        }

        function showResults() {
            resultsEl.classList.add('visible');
        }

        function hideResults() {
            resultsEl.classList.remove('visible');
        }

        // Helper to dynamically load a script
        function loadScript(url) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = url;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
            });
        }

        // Initialize WebPerl and load sloccount
        async function initializeWebPerl() {
            try {
                console.log('initializeWebPerl() starting...');
                showStatus('Loading Perl WebAssembly runtime...', 'info');

                // Wait for Perl to reach Running state (triggered by embedded script)
                console.log('Waiting for Perl to be Running...');
                while (Perl.state !== 'Running') {
                    console.log('Current Perl state:', Perl.state);
                    await new Promise(resolve => setTimeout(resolve, 100));
                }
                console.log('Perl is now Running!');

                showStatus('Loading SLOCCount Perl scripts...', 'info');

                // Load sloccount scripts from local zip file
                const zipUrl = './lib/sloccount-perl.zip';

                // Fetch the zip file
                const response = await fetch(zipUrl);
                if (!response.ok) {
                    throw new Error('Failed to fetch sloccount scripts');
                }

                const zipBlob = await response.blob();
                const zip = await JSZip.loadAsync(zipBlob);

                showStatus('Extracting Perl scripts...', 'info');

                // Load ALL counter scripts (they all end with _count)
                const scriptsToLoad = [
                    'python_count', 'perl_count', 'ruby_count', 'generic_count',
                    'javascript_count', 'sh_count', 'sql_count', 'lisp_count',
                    'asm_count', 'ada_count', 'awk_count', 'cobol_count', 'fortran_count',
                    'f90_count', 'haskell_count', 'makefile_count', 'modula3_count',
                    'objc_count', 'sed_count', 'tcl_count', 'vbasic_count', 'exp_count',
                    'csh_count', 'batch_count', 'vbscript_count', 'autohotkey_count',
                    'autoit_count', 'innosetup_count', 'lex_count'
                ];

                for (const scriptName of scriptsToLoad) {
                    if (zip.files[scriptName]) {
                        const content = await zip.files[scriptName].async('text');
                        slocScripts[scriptName] = content;
                    }
                }

                console.log('Loaded', Object.keys(slocScripts).length, 'counter scripts from zip');

                // Load modern language counter scripts from lib/sloc/
                const modernScripts = [
                    'kotlin_count', 'swift_count', 'dart_count', 'scala_count',
                    'groovy_count', 'elixir_count', 'julia_count', 'fsharp_count',
                    'rust_count', 'go_count'
                ];

                for (const scriptName of modernScripts) {
                    try {
                        const response = await fetch(`./lib/sloc/${scriptName}`);
                        if (response.ok) {
                            const content = await response.text();
                            slocScripts[scriptName] = content;
                        }
                    } catch (error) {
                        console.warn(`Failed to load ${scriptName}:`, error);
                    }
                }

                console.log('Total loaded:', Object.keys(slocScripts).length, 'counter scripts');

                // Make scripts available to Perl via window object
                window.counterScripts = slocScripts;

                showStatus('Loading WebAssembly counters...', 'info');

                // Load WASM modules for C-based counters
                // We'll store their output in this array
                window.wasmOutput = [];

                // Load c_count WASM (used by many languages)
                const c_count_module = await loadScript('./lib/wasm/c_count.js');
                window.CCountModule = await createCCountModule({
                    print: (text) => { window.wasmOutput.push(text); },
                    printErr: (text) => { console.error('c_count WASM:', text); },
                    noInitialRun: true,
                    stdin: () => null,
                    // Disable prompts for input
                    prompt: () => null
                });
                console.log('Loaded c_count WASM module');

                showStatus('WebAssembly counters loaded!', 'success');

                perlReady = true;

                analyzePasteBtn.textContent = 'Analyze Code';
                analyzePasteBtn.disabled = false;
                analyzeRepoBtn.textContent = 'Analyze Repository';
                analyzeRepoBtn.disabled = false;
                analyzeZipBtn.textContent = 'Analyze ZIP';
                analyzeZipBtn.disabled = false;

                showStatus('Ready to analyze code!', 'success');
                setTimeout(hideStatus, 2000);
            } catch (error) {
                showStatus('Failed to initialize: ' + error.message, 'error');
                console.error('Initialization error:', error);
            }
        }

        // Run sloccount using REAL sloccount Perl scripts and WASM counters
        // Run sloccount using REAL sloccount Perl scripts and WASM counters
        async function runSloccount(files, salary = 56286) {
            try {
                // Map extensions to counter scripts and whether they need WASM
                const extToCounter = {
                    'py': { counter: 'python_count', type: 'perl', lang: 'Python' },
                    'rb': { counter: 'ruby_count', type: 'perl', lang: 'Ruby' },
                    'pl': { counter: 'perl_count', type: 'perl', lang: 'Perl' },
                    'pm': { counter: 'perl_count', type: 'perl', lang: 'Perl' },
                    'sh': { counter: 'sh_count', type: 'wasm', lang: 'Shell' },
                    'bash': { counter: 'sh_count', type: 'wasm', lang: 'Shell' },
                    'js': { counter: 'javascript_count', type: 'wasm', lang: 'JavaScript' },
                    'ts': { counter: 'javascript_count', type: 'wasm', lang: 'TypeScript' },
                    'java': { counter: 'generic_count', type: 'wasm', lang: 'Java' },
                    'c': { counter: 'generic_count', type: 'wasm', lang: 'C' },
                    'h': { counter: 'generic_count', type: 'wasm', lang: 'C' },
                    'cpp': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
                    'cc': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
                    'cxx': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
                    'hpp': { counter: 'generic_count', type: 'wasm', lang: 'C++' },
                    'go': { counter: 'go_count', type: 'perl', lang: 'Go' },
                    'rs': { counter: 'rust_count', type: 'perl', lang: 'Rust' },
                    'php': { counter: 'generic_count', type: 'wasm', lang: 'PHP' },
                    'sql': { counter: 'sql_count', type: 'perl', lang: 'SQL' },
                    // Modern languages (post-2001)
                    'kt': { counter: 'kotlin_count', type: 'perl', lang: 'Kotlin' },
                    'kts': { counter: 'kotlin_count', type: 'perl', lang: 'Kotlin' },
                    'swift': { counter: 'swift_count', type: 'perl', lang: 'Swift' },
                    'dart': { counter: 'dart_count', type: 'perl', lang: 'Dart' },
                    'scala': { counter: 'scala_count', type: 'perl', lang: 'Scala' },
                    'groovy': { counter: 'groovy_count', type: 'perl', lang: 'Groovy' },
                    'ex': { counter: 'elixir_count', type: 'perl', lang: 'Elixir' },
                    'exs': { counter: 'elixir_count', type: 'perl', lang: 'Elixir' },
                    'jl': { counter: 'julia_count', type: 'perl', lang: 'Julia' },
                    'fs': { counter: 'fsharp_count', type: 'perl', lang: 'F#' },
                    'fsx': { counter: 'fsharp_count', type: 'perl', lang: 'F#' },
                };

                // Group files by counter and language
                const filesByCounter = {};
                for (const file of files) {
                    const match = file.filename.match(/\.([^.]+)$/);
                    if (!match) continue;

                    const ext = match[1].toLowerCase();
                    const counterInfo = extToCounter[ext];
                    if (!counterInfo) continue;

                    const key = `${counterInfo.type}:${counterInfo.counter}:${counterInfo.lang}`;
                    if (!filesByCounter[key]) {
                        filesByCounter[key] = {
                            type: counterInfo.type,
                            counter: counterInfo.counter,
                            lang: counterInfo.lang,
                            files: []
                        };
                    }
                    filesByCounter[key].files.push(file);
                }

                const langStats = {};
                let totalLines = 0;

                // Process each counter group
                for (const key in filesByCounter) {
                    const group = filesByCounter[key];

                    if (group.type === 'perl') {
                        // Run Perl counter script
                        const script = window.counterScripts[group.counter];
                        if (!script) {
                            console.warn(`Counter script ${group.counter} not found`);
                            continue;
                        }

                        // Write files to VFS
                        const filePaths = [];
                        for (const file of group.files) {
                            // Use just the basename to avoid directory issues
                            const basename = file.filename.split('/').pop();
                            const path = `/tmp/${basename}`;

                            // Store content in window for Perl to access
                            window._tempFileContent = file.content;

                            Perl.eval(`
                                use WebPerl qw/js/;
                                use File::Path qw(make_path);

                                my $path = '${path}';
                                my $content = js('window')->{_tempFileContent};

                                # Create parent directories if needed
                                if ($path =~ m{^(.+)/[^/]+$}) {
                                    make_path($1);
                                }

                                open(my $fh, '>', $path) or die "Cannot write $path: $!";
                                print $fh $content;
                                close($fh);
                            `);
                            filePaths.push(path);
                        }
                        window._tempFileContent = null;

                        // Run counter and capture output
                        window.perlCounterOutput = '';
                        Perl.eval(`
                            use warnings;
                            use WebPerl qw/js/;

                            my $script = js('window')->{counterScripts}{'${group.counter}'};
                            @ARGV = (${filePaths.map(p => `'${p}'`).join(', ')});

                            my $output = '';
                            open(my $stdout_fh, '>', \\$output) or die "Cannot redirect: $!";
                            select $stdout_fh;

                            eval $script;
                            if ($@) {
                                $output .= "ERROR: $@";
                            }

                            select STDOUT;
                            close($stdout_fh);

                            js('window')->{perlCounterOutput} = $output;
                        `);

                        // Parse output
                        const output = window.perlCounterOutput;
                        const lines = output.split('\n');
                        let groupLines = 0;
                        let groupFiles = 0;

                        for (const line of lines) {
                            if (line.trim() && !line.startsWith('Total:')) {
                                const match = line.match(/^(\d+)\s+/);
                                if (match) {
                                    groupLines += parseInt(match[1]);
                                    groupFiles++;
                                }
                            }
                        }

                        if (!langStats[group.lang]) {
                            langStats[group.lang] = { lines: 0, files: 0 };
                        }
                        langStats[group.lang].lines += groupLines;
                        langStats[group.lang].files += groupFiles;
                        totalLines += groupLines;

                    } else if (group.type === 'wasm') {
                        // Run WASM c_count
                        const CCount = window.CCountModule;
                        if (!CCount) {
                            console.warn('c_count WASM module not loaded');
                            continue;
                        }

                        // Write files to WASM VFS
                        const filePaths = [];
                        for (const file of group.files) {
                            // Use just the basename to avoid directory issues
                            const basename = file.filename.split('/').pop();
                            const path = `/tmp/${basename}`;
                            CCount.FS.writeFile(path, file.content);
                            filePaths.push(path);
                        }

                        // Clear output and run
                        window.wasmOutput = [];
                        CCount.callMain(filePaths);

                        // Parse output
                        const output = window.wasmOutput.join('\n');
                        const lines = output.split('\n');
                        let groupLines = 0;
                        let groupFiles = 0;

                        for (const line of lines) {
                            if (line.trim() && !line.startsWith('Total:')) {
                                const match = line.match(/^(\d+)\s+/);
                                if (match) {
                                    groupLines += parseInt(match[1]);
                                    groupFiles++;
                                }
                            }
                        }

                        if (!langStats[group.lang]) {
                            langStats[group.lang] = { lines: 0, files: 0 };
                        }
                        langStats[group.lang].lines += groupLines;
                        langStats[group.lang].files += groupFiles;
                        totalLines += groupLines;
                    }
                }

                // Calculate COCOMO using editable values
                const overheadCoeff = parseFloat(document.getElementById('overhead-input')?.value || 2.4);
                const overheadMultiplier = parseFloat(document.getElementById('overhead-multiplier-input')?.value || 2.4);

                const kloc = totalLines / 1000.0;
                const effortMonths = overheadCoeff * Math.pow(kloc, 1.05);
                const personYears = effortMonths / 12.0;
                const totalCost = personYears * salary * overheadMultiplier;
                const scheduleMonths = 2.5 * Math.pow(effortMonths, 0.38);

                // Format results
                const results = [];
                for (const lang in langStats) {
                    results.push({
                        language: lang,
                        lines: langStats[lang].lines,
                        files: langStats[lang].files
                    });
                }

                results.cocomo = {
                    effort: personYears,
                    cost: totalCost,
                    schedule: scheduleMonths
                };

                return results;
            } catch (error) {
                console.error('runSloccount error:', error);
                throw new Error('Failed to run sloccount: ' + error.message);
            }
        }

        // Analyze pasted code
        async function analyzePastedCode() {
            const code = codeInput.value.trim();
            const filename = filenameInput.value.trim();

            if (!code) {
                showStatus('Please paste some code to analyze', 'error');
                return;
            }

            if (!filename) {
                showStatus('Please provide a filename to detect the language', 'error');
                return;
            }

            try {
                analyzePasteBtn.disabled = true;
                showStatus('Analyzing code with Perl sloccount...', 'info');

                const files = [{ filename: filename, content: code }];
                const salary = parseInt(getSalaryInput().value) || 56286;

                const results = await runSloccount(files, salary);
                currentFiles = files; // Store for recalculation

                displayResults(results);

                showStatus('Analysis complete!', 'success');
                setTimeout(hideStatus, 3000);
            } catch (error) {
                showStatus('Analysis failed: ' + error.message, 'error');
                console.error('Analysis error:', error);
            } finally {
                analyzePasteBtn.disabled = false;
            }
        }

        // Analyze GitHub repository
        async function analyzeGitHubRepo() {
            let repoUrl = repoInput.value.trim();

            if (!repoUrl) {
                showStatus('Please provide a GitHub repository URL or owner/repo', 'error');
                return;
            }

            let owner, repo;

            // Try to parse as owner/repo shorthand first
            const shorthandMatch = repoUrl.match(/^([^\/\s]+)\/([^\/\s]+)$/);
            if (shorthandMatch) {
                owner = shorthandMatch[1];
                repo = shorthandMatch[2].replace('.git', '');
            } else {
                // Parse as full GitHub URL
                const urlMatch = repoUrl.match(/github\.com\/([^\/]+)\/([^\/]+)/);
                if (!urlMatch) {
                    showStatus('Invalid format. Use: owner/repo or https://github.com/owner/repo', 'error');
                    return;
                }
                owner = urlMatch[1];
                repo = urlMatch[2].replace('.git', '');
            }

            try {
                analyzeRepoBtn.disabled = true;
                showStatus('Fetching repository information from GitHub API...', 'info');

                // First, get the repository info to determine the default branch
                const repoInfoUrl = `https://api.github.com/repos/${owner}/${repo}`;
                const repoInfoResponse = await fetch(repoInfoUrl);

                if (!repoInfoResponse.ok) {
                    if (repoInfoResponse.status === 404) {
                        throw new Error('Repository not found. Make sure the repository exists and is public.');
                    } else if (repoInfoResponse.status === 403) {
                        throw new Error('API rate limit exceeded. Please try again later.');
                    }
                    throw new Error(`Failed to fetch repository info: ${repoInfoResponse.statusText}`);
                }

                const repoInfo = await repoInfoResponse.json();
                const defaultBranch = repoInfo.default_branch || 'main';

                showStatus('Fetching repository tree from GitHub API...', 'info');

                // Use GitHub Trees API to get all files
                const treeUrl = `https://api.github.com/repos/${owner}/${repo}/git/trees/${defaultBranch}?recursive=1`;
                const treeResponse = await fetch(treeUrl);

                if (!treeResponse.ok) {
                    if (treeResponse.status === 404) {
                        throw new Error('Repository tree not found. Make sure the repository exists and is public.');
                    } else if (treeResponse.status === 403) {
                        throw new Error('API rate limit exceeded. Please try again later.');
                    }
                    throw new Error(`Failed to fetch repository tree: ${treeResponse.statusText}`);
                }

                const treeData = await treeResponse.json();

                // Check if the tree was truncated by GitHub
                if (treeData.truncated) {
                    const zipUrl = `https://github.com/${owner}/${repo}/archive/refs/heads/${defaultBranch}.zip`;
                    showStatus(`⚠️ This repository is too large and the GitHub API truncated the file list. Please download the full repository as a ZIP file and use the "Upload ZIP" tab instead: <a href="${zipUrl}" style="color: #004085; text-decoration: underline;">${zipUrl}</a>`, 'error', true);
                    return; // Stop processing - user must use ZIP upload
                }

                // Filter for code files only
                const codeExtensions = /\.(c|h|cpp|cc|cxx|hpp|py|java|js|ts|rb|pl|pm|php|go|rs|cs|sh|bash|html|css|sql|r|swift|kt|kts|scala|lua|vim|dart|groovy|ex|exs|jl|fs|fsx)$/i;
                const codeFiles = treeData.tree.filter(item =>
                    item.type === 'blob' && codeExtensions.test(item.path)
                );

                if (codeFiles.length === 0) {
                    throw new Error('No code files found in repository');
                }

                showStatus(`Fetching ${codeFiles.length} code files...`, 'info');

                // Fetch files in batches to avoid overwhelming the browser
                const files = [];
                const batchSize = 10;

                for (let i = 0; i < codeFiles.length; i += batchSize) {
                    const batch = codeFiles.slice(i, i + batchSize);
                    const batchPromises = batch.map(async (file) => {
                        try {
                            // Use raw.githubusercontent.com which has permissive CORS
                            const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${defaultBranch}/${file.path}`;
                            const response = await fetch(rawUrl);

                            if (response.ok) {
                                const content = await response.text();
                                return { filename: file.path, content: content };
                            }
                            return null;
                        } catch (error) {
                            console.warn(`Failed to fetch ${file.path}:`, error);
                            return null;
                        }
                    });

                    const batchResults = await Promise.all(batchPromises);
                    files.push(...batchResults.filter(f => f !== null));

                    // Update progress
                    const progress = Math.min(i + batchSize, codeFiles.length);
                    showStatus(`Fetched ${progress}/${codeFiles.length} files...`, 'info');
                }

                if (files.length === 0) {
                    throw new Error('Failed to fetch any code files from repository');
                }

                showStatus(`Analyzing ${files.length} files with Perl sloccount...`, 'info');

                const salary = parseInt(getSalaryInput().value) || 56286;
                const results = await runSloccount(files, salary);
                currentFiles = files; // Store for recalculation

                displayResults(results);

                showStatus('Analysis complete!', 'success');
                setTimeout(hideStatus, 3000);
            } catch (error) {
                showStatus('Analysis failed: ' + error.message, 'error');
                console.error('Analysis error:', error);
            } finally {
                analyzeRepoBtn.disabled = false;
            }
        }

        // Analyze uploaded ZIP file
        let zipAnalysisInProgress = false;
        async function analyzeZipFile() {
            if (zipAnalysisInProgress) {
                console.warn('Analysis already in progress, ignoring click');
                return;
            }

            zipAnalysisInProgress = true;
            const fileInput = zipInput.files[0];

            if (!fileInput) {
                showStatus('Please select a ZIP file to upload', 'error');
                zipAnalysisInProgress = false;
                return;
            }

            if (!fileInput.name.endsWith('.zip')) {
                showStatus('Please upload a ZIP file', 'error');
                zipAnalysisInProgress = false;
                return;
            }

            try {
                analyzeZipBtn.disabled = true;
                showStatus('Loading ZIP file...', 'info');

                // Use Blob URL with fetch
                const blobUrl = URL.createObjectURL(fileInput);
                const response = await fetch(blobUrl);
                const zipBlob = await response.arrayBuffer();
                URL.revokeObjectURL(blobUrl);

                const zip = await JSZip.loadAsync(zipBlob);

                showStatus('Extracting code files...', 'info');

                // Extract all code files
                const files = [];
                const codeExtensions = /\.(c|h|cpp|cc|cxx|hpp|py|java|js|ts|rb|pl|pm|php|go|rs|cs|sh|bash|html|css|sql|r|swift|kt|kts|scala|lua|vim|dart|groovy|ex|exs|jl|fs|fsx)$/i;

                for (const fileName in zip.files) {
                    const file = zip.files[fileName];

                    if (!file.dir && codeExtensions.test(fileName)) {
                        try {
                            const content = await file.async('text');
                            files.push({ filename: fileName, content: content });
                        } catch (error) {
                            console.warn(`Failed to extract ${fileName}:`, error);
                        }
                    }
                }

                if (files.length === 0) {
                    throw new Error('No code files found in ZIP file');
                }

                showStatus(`Analyzing ${files.length} files with Perl sloccount...`, 'info');

                const salary = parseInt(getSalaryInput().value) || 56286;
                const results = await runSloccount(files, salary);
                currentFiles = files; // Store for recalculation

                displayResults(results);

                showStatus('Analysis complete!', 'success');
                setTimeout(hideStatus, 3000);
            } catch (error) {
                showStatus('Analysis failed: ' + error.message, 'error');
                console.error('ZIP Analysis error:', error);
            } finally {
                analyzeZipBtn.disabled = false;
                zipAnalysisInProgress = false;
            }
        }

        // Calculate COCOMO estimates (Basic COCOMO model)
        function calculateCOCOMO(totalLines) {
            // Convert SLOC to KLOC (thousands of lines)
            const kloc = totalLines / 1000;

            // Basic COCOMO: Effort = 2.4 * (KLOC)^1.05 person-months
            const effort = 2.4 * Math.pow(kloc, 1.05);

            // Convert person-months to person-years
            const personYears = effort / 12;

            // Average salary: $56,286/year (from original sloccount)
            // Overhead multiplier: 2.4
            const avgSalary = 56286;
            const overhead = 2.4;
            const totalCost = personYears * avgSalary * overhead;

            return {
                personYears: personYears,
                cost: totalCost
            };
        }

        // Display results
        function displayResults(results) {
            const totalLines = results.reduce((sum, r) => sum + r.lines, 0);
            const totalFiles = results.reduce((sum, r) => sum + r.files, 0);
            const totalLanguages = results.length;

            // Use COCOMO estimates from Perl (if available)
            const cocomo = results.cocomo || { effort: 0, cost: 0, schedule: 0 };

            document.getElementById('total-lines').textContent = totalLines.toLocaleString();
            document.getElementById('total-languages').textContent = totalLanguages;
            document.getElementById('total-files').textContent = totalFiles;
            document.getElementById('total-cost').textContent = '$' + Math.round(cocomo.cost).toLocaleString();
            document.getElementById('total-effort').textContent = cocomo.effort.toFixed(2);

            // Sort by lines descending
            results.sort((a, b) => b.lines - a.lines);

            const tbody = document.getElementById('language-tbody');
            tbody.innerHTML = '';

            results.forEach(result => {
                const percentage = ((result.lines / totalLines) * 100).toFixed(1);
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td class="language-name">${result.language}</td>
                    <td>${result.lines.toLocaleString()}</td>
                    <td class="percentage">${percentage}%</td>
                    <td>${result.files}</td>
                `;
                tbody.appendChild(row);
            });

            showResults();
        }

        // Event listeners
        analyzePasteBtn.addEventListener('click', analyzePastedCode);
        analyzeRepoBtn.addEventListener('click', analyzeGitHubRepo);
        analyzeZipBtn.addEventListener('click', analyzeZipFile);

        // Enter key support for GitHub repo input
        repoInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                analyzeGitHubRepo();
            }
        });

        // Set up event listeners for COCOMO inputs
        setTimeout(() => {
            const salaryInput = getSalaryInput();
            const overheadInput = document.getElementById('overhead-input');
            const overheadMultiplierInput = document.getElementById('overhead-multiplier-input');
            const year2000Radio = document.getElementById('year-2000');
            const year2025Radio = document.getElementById('year-2025');

            // Salary input
            if (salaryInput) {
                salaryInput.addEventListener('change', recalculateWithSalary);
                salaryInput.addEventListener('input', () => {
                    clearTimeout(salaryInput.recalcTimer);
                    salaryInput.recalcTimer = setTimeout(recalculateWithSalary, 500);
                });
            }

            // Overhead coefficient input
            if (overheadInput) {
                overheadInput.addEventListener('change', recalculateWithSalary);
                overheadInput.addEventListener('input', () => {
                    clearTimeout(overheadInput.recalcTimer);
                    overheadInput.recalcTimer = setTimeout(recalculateWithSalary, 500);
                });
            }

            // Overhead multiplier input
            if (overheadMultiplierInput) {
                overheadMultiplierInput.addEventListener('change', recalculateWithSalary);
                overheadMultiplierInput.addEventListener('input', () => {
                    clearTimeout(overheadMultiplierInput.recalcTimer);
                    overheadMultiplierInput.recalcTimer = setTimeout(recalculateWithSalary, 500);
                });
            }

            // Year preset radio buttons
            if (year2000Radio) {
                year2000Radio.addEventListener('change', () => {
                    if (year2000Radio.checked) {
                        overheadInput.value = 2.4;
                        salaryInput.value = 56286;
                        overheadMultiplierInput.value = 2.4;
                        recalculateWithSalary();
                    }
                });
            }

            if (year2025Radio) {
                year2025Radio.addEventListener('change', () => {
                    if (year2025Radio.checked) {
                        overheadInput.value = 2.94;
                        salaryInput.value = 133080;
                        overheadMultiplierInput.value = 1.85;
                        recalculateWithSalary();
                    }
                });
            }
        }, 100);

        // Initialize when page loads
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initializeWebPerl);
        } else {
            initializeWebPerl();
        }
    </script>

    <div id="cost-estimates-info" style="max-width: 900px; margin: 40px auto 20px; padding: 20px; background: #f8f9fa; border-radius: 4px; border-left: 4px solid #007bff;">
        <h3 style="margin-top: 0;">About Cost Estimates</h3>
        <p style="margin: 10px 0;">The cost and effort estimates use the <strong>Basic COCOMO model</strong> (Constructive Cost Model), a widely-used software engineering cost estimation method developed by Barry Boehm.</p>

        <div style="background: #fff3cd; border: 2px solid #ffc107; border-radius: 5px; padding: 15px; margin: 15px 0;">
            <p style="margin: 0 0 10px 0; font-weight: bold; color: #856404;">⚠️ These are EXTREMELY ROUGH estimates</p>
            <p style="margin: 0 0 10px 0; font-size: 14px; color: #856404;">
                Actual costs vary wildly based on project complexity, team experience, location, development practices, and many other factors.
                Use these numbers only as a very rough ballpark estimate.
            </p>
            <div style="margin-top: 10px;">
                <label style="display: block; margin-bottom: 5px; font-weight: bold; color: #856404;">Using estimates from:</label>
                <div style="display: flex; gap: 10px; align-items: center;">
                    <label style="cursor: pointer; display: flex; align-items: center; gap: 5px;">
                        <input type="radio" name="estimate-year" value="2000" checked id="year-2000">
                        <span>Year 2000 (Original SLOCCount)</span>
                    </label>
                    <label style="cursor: pointer; display: flex; align-items: center; gap: 5px;">
                        <input type="radio" name="estimate-year" value="2025" id="year-2025">
                        <span>Year 2025 (Updated)</span>
                    </label>
                </div>
                <p style="margin: 8px 0 0 0; font-size: 12px; color: #856404; font-style: italic;">
                    Note: The 2025 values are <strong>very untrustworthy guesses</strong> from <a href="https://chatgpt.com/share/68f7e0ac-00c4-8006-979e-64d1f0162283" style="color: #856404; text-decoration: underline;">this ChatGPT conversation</a>, not based on rigorous research.
                </p>
            </div>
        </div>

        <p style="margin: 10px 0;"><strong>Key assumptions (editable):</strong></p>
        <ul style="margin: 5px 0; padding-left: 20px;">
            <li>Effort coefficient: <input type="number" id="overhead-input" value="2.4" min="0.1" max="10" step="0.1" style="width: 60px; padding: 2px 5px; border: 1px solid #ccc; border-radius: 3px;"> × (KLOC)<sup>1.05</sup> person-months</li>
            <li>Average developer salary: $<input type="number" id="salary-input" value="56286" min="1000" max="1000000" step="1000" style="width: 100px; padding: 2px 5px; border: 1px solid #ccc; border-radius: 3px;">/year</li>
            <li>Overhead multiplier: <input type="number" id="overhead-multiplier-input" value="2.4" min="1" max="10" step="0.1" style="width: 60px; padding: 2px 5px; border: 1px solid #ccc; border-radius: 3px;">× (includes benefits, equipment, office space, etc.)</li>
        </ul>

        <p style="margin: 10px 0; font-size: 14px;"><em>This tool uses the WebAssembly build of Perl running actual SLOCCount algorithms from <a href="https://github.com/licquia/sloccount">licquia/sloccount</a>.</em></p>
    </div>

    <!-- Embedded Perl script to initialize Perl into Running state -->
    <!-- This must come AFTER the main JavaScript to avoid blocking -->
    <script type="text/perl">
        # Minimal script to put Perl into Running state
        1;
    </script>
</body>
</html>
